package com.yxw.yxnet_cd_center.common.utils;

import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.util.SortedMap;

/**
 * @desc:sha1和sha256签名算法
 */
@Slf4j
public class SHASignUtil {

    /**
     * sha1加密
     */
    public static String SHA1Hex(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        } else {
            return DigestUtils.sha1Hex(str);
        }
    }


    /**
     * 对所有待签名参数按照字段名的ASCII 码从小到大排序
     */
    public static String mapLink(SortedMap<String, Object> map) {
        return Joiner.on("&").withKeyValueSeparator("=").join(map);
    }

    /**
     * sha256签名算法
     */
    public static String SHA256(String str) 
    {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } 
        catch (Exception e) 
        {
            System.out.println(e.toString());
            //throw e;
        }
        return encodeStr;
    }
    /**
     * sha512签名算法
     */
    public static String SHA512(String str) 
    {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-512");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } 
        catch (Exception e) 
        {
            System.out.println(e.toString());
            //throw e;
        }
        return encodeStr;
    }
    // byte转换成16进制
    protected static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }
}

